package handlers

import (
	"github.com/gin-gonic/gin"
	"red-book-mgr/model"
	"red-book-mgr/pkg"
	"strconv"
)

func Login(c *gin.Context) {
	tel := c.PostForm("tel")
	password := c.PostForm("password")
	var user model.User
	err := model.DB.Where("tel = ? and password = ?", tel, password).First(&user).Error
	if err == nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能重复注册",
		})
		return
	}
	data := model.User{
		Tel:      tel,
		Password: pkg.Md5str1(password),
	}
	err = model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登入失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "登入成功",
		})
		return
	}
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "1"))
	offset := (page - 1) * size
	var count int64
	model.DB.Model(&model.Title{}).Count(&count)
	var title []model.Title
	err := model.DB.Offset(offset).Limit(size).Find(&title).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询成功",
			"data": gin.H{
				"count": count,
				"data":  title,
			},
		})
		return
	}
}
